"""
    Author:
    Date: 2019-12-19

    CPA管理类
"""

import env
import itsdangerous
from django.conf import settings

from utils import db

# 错误码定义
CPA_ERROR_NO_ERROR                      = {'id': 0, 'message': 'OK'}
CPA_ERROR_INVALID_SECRET                = {'id': 1, 'message': '无效的密钥!'}
CPA_ERROR_INVALID_TOKEN                 = {'id': 2, 'message': '无效的TOKEN!'}


def is_valid_secret(client_id, client_secret):
    """ 检测是否合法 """
    saved_secret = settings.CPA_SECRETS.get(client_id, None)
    if saved_secret is None:
        return False

    return client_secret == saved_secret

def fetch_access_token(client_id):
    """ 分配一个JWT """
    s = itsdangerous.TimedJSONWebSignatureSerializer(settings.CPA_JWT_SECRET, expires_in=2*3600)
    data = {
        'client_id': client_id,
    }
    access_token = s.dumps(data).decode('utf-8')
    return access_token

def verify_access_token(access_token):
    """ 验证access token是否合法 """
    s = itsdangerous.TimedJSONWebSignatureSerializer(settings.CPA_JWT_SECRET, expires_in=2*3600)
    try:
        data = s.loads(access_token)
        return data['client_id']
    except itsdangerous.BadSignature as e:
        return None

def is_device_exists(device_id):
    """ 判断指定的设备是否存在 """
    if device_id is None:
        return False

    device_id = device_id.lower()
    sql = f'''
        SELECT      id
        FROM        cmf_users_activation
        WHERE       device_id=%(device_id)s
        LIMIT       1;
    '''
    params = {
        'device_id': device_id,
    }
    data = db.query_data_from_db(sql, params)
    return len(data) == 1

def create_new_device(device_id):
    """ 创建新设备 """
    if not env.DEBUG:
        return
    device_id = device_id.lower()
    sql = '''
        INSERT INTO cmf_users_activation
        SET         bundle_id=%(bundle_id)s,
                    channel=%(channel)s,
                    device_id=%(device_id)s;
    '''
    params = {
        'bundle_id': 'test bundle id',
        'channel': 'test channel',
        'device_id': device_id,
    }
    affected_rows = db.execute_sql(sql, params)
    return affected_rows == 1

if __name__ == '__main__':
    print('ok')
